<?php

namespace app\chat\controller;

use app\common\library\Wxtoken;
use app\common\controller\Frontend;
use app\common\model\User;
use fast\Random;
use think\log;
use fast\Tool;
use think\config;
use app\common\model\Admin;
use app\common\model\AuthGroupAccess;
use think\Db;
use app\common\model\KfStyle;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Chat
 *
 * @author xpz
 */
class Chat extends Frontend {

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    private $appId;
    private $appSecret;
    
    private $subscribeMessage = "";
    private $acanMessage = "";
    private $unsubscribeMessage = "";

    private $getAccountExpireTime = 604800;


    public function _initialize() {
        parent::_initialize();
        $this->appId = Config::get('xpz.app_id');
        $this->appSecret = Config::get('xpz.app_secret');
        $this->subscribeMessage = Config::get('greeting.wx_follow');
        $this->acanMessage = Config::get('greeting.wx_followed');
        $this->unsubscribeMessage = Config::get('greeting.wx_cancel_follow');
    }
    
    
    
    public function test(){
        $contentStr = $this->getJsCode('oGj4w6nLJroWp5yjc8GC8RfNQhIE');
        echo $contentStr;exit;
//        echo "test";exit;
//        $salt = Random::uuid();
//        echo $salt;
//        exit;
//        $touser = 'oGj4w6nLJroWp5yjc8GC8RfNQhIE';
//        $this->addKf($touser);
//        exit;
//        $content = "3333";
//        $uuid= 'B42ACB42-C08B-02D9-42BD-FE8B56577727';
//        Tool::wxMessageNotice($touser, $content, $uuid);
//        var_dump(Config::get('xpz.my_log_show'));exit;
//        echo $this->appSecret;exit;
//        $token = $this->getToken();
//        echo $token;
//        exit;
        //if ($this->checkSignature()) {
//    echo $_GET['echostr'];
//}
//        exit;
        $users = $this->createuserinfo('oGj4w6nLJroWp5yjc8GC8RfNQhIE');//获取用户信息
        $this->subscribeSyacUser($users);
    }

    public function index() {
        if(Config::get('xpz.wx_check_signature') == 1){
            $this->checkSignature();
            echo $_GET['echostr'];
            exit;
        }
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            // 微信消息类型
            $RX_TYPE = trim($postObj->MsgType);
//            file_put_contents('5.txt', $postStr);
            switch ($RX_TYPE) {
                case "text":
                    // 文本消息
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    // 事件推送
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: " . $RX_TYPE;
                    break;
            }
            echo $resultStr;
        } else {
            echo "";
            exit;
        }
    }

    /**
     * 微信文本消息
     * @param $postObj
     */
    private function handleText($postObj) {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        if (!empty($keyword)) {
            if($keyword == '完善公司信息' || $keyword == "2"){
//                file_put_contents('1.txt', $fromUsername);
                $msgType = "text";
                $userInfo = model("User")->where(['openid'=>$fromUsername])->find();
                if(empty($userInfo['id'])){//请先关注公众号完成会员注册
                    $contentStr = "请先关注公众号完成会员注册！";
                } else if(!empty($userInfo['company_id'])){//此用户已绑定公司
                    $contentStr = "此用户已绑定公司，不能重复绑定！";
                } else {
                    $contentStr = getRegCompanyA($fromUsername,$userInfo['id']);
                }

                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else if($keyword == '获取客服代码' || $keyword == "3"){
                $msgType = "text";
                $contentStr = $this->getJsCode($fromUsername);
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else if($keyword == '帮助' || $keyword == "1"){
                $msgType = "text";
                $contentStr = $this->getHelpContent();
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else {
                $msgType = "text";
                $contentStr = "欢迎您关注";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }
            
        } else {
            echo "请输入...";
        }
    }

    /**
     * 获取时间消息并解析相应参数
     * 提供数据简单推送(自动回复)
     * @param $object
     *
     * @return string
     */
    private function handleEvent($object) {
        $contentStr = "";
        switch ($object->Event) {
            case "subscribe":
//                $userStr = "你的前端账号为：【".$username."】，密码为：【".$salt."】，请您在24小时之内登录系统修改密码！<a href='".Tool::getDomain()."/index.php/index/user/login.html'>点击登录</a>";
                $contentStr = $this->subscribeMessage."\r\n".$this->getHelpContent();
                
                $openid = (string) $object->FromUserName; //数据类型转换为字符串
//                $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_1232313这种类型
                $users = $this->createuserinfo($openid);//获取用户信息
                //同步到数据库
                $this->subscribeSyacUser($users);
                break;
            case "SCAN":
                $contentStr = $this->acanMessage;
                $openid = (string) $object->FromUserName; //数据类型转换为字符串
//                $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_12213213这种类型
                $this->createuserinfo($openid);//获取用户信息
                break;
            case "unsubscribe";
                $contentStr = $this->unsubscribeMessage;
                $openid = (string) $object->FromUserName; //数据类型转换为字符串
//                file_put_contents('1115.txt', $openid);
//                $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_1232313这种类型
//                $users = $this->createuserinfo($openid);//获取用户信息
                //同步到数据库
                $this->unSubscribeSyacUser($openid);
                break;
        }
//        $tmpdd = "EventKey:" . $object->EventKey . "=>FromUserName" . $object->FromUserName;
//        file_put_contents('115.txt', $tmpdd);
        
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }
    
    //取消关注同步数据
    private function unSubscribeSyacUser($openid){
        if(!empty($openid)){
            $userOne = User::get(['openid'=>$openid]);
            if(isset($userOne['openid']) && !empty($userOne['openid'])){
                User::update(['status'=>'hidden','updatetime'=>time()],['openid'=>$openid]);
            }
        }
    }
    
    //关注同步数据
    private function subscribeSyacUser($users){
        $userOne = User::get(['openid'=>$users['openid']]);
        if(isset($userOne['openid']) && !empty($userOne['openid'])){
            User::update(['status'=>'normal','updatetime'=>time()],['openid'=>$users['openid']]);
        } else {

            $time = time();
            $ip = request()->ip();
            $salt = Random::alnum();
            $username = $this->short_md5();
//            $salt = Random::alnum();
            $password = getEncryptPassword($salt,$salt);
            $params = [
                'nickname'  =>$users['nickname'],
                'salt'      => $salt,
                'jointime'  => $time,
                'joinip'    => $ip,
                'logintime' => $time,
                'loginip'   => $ip,
                'prevtime'  => $time,
                'status'    => 'normal',
                'avatar' => $users['avatar'],
                'openid' => $users['openid'],
                'gender' => $users['sex'],
                'username' =>$username, 
                'password' =>$password,
                'createtime' => $time,

            ];
            $uid = User::insertGetId($params, true);

            if(!empty($uid)){
            } else {
                Tool::mylog(true, "关注公众号自动创建账号失败！","微信openid：".$users['nickname']."===微信昵称=》".$users['nickname'] , 'wx_test_account_error');
            }
            
        }
        
    }

    /**
     * 消息回复模板
     * @param     $object
     * @param     $content
     * @param int $flag
     *
     * @return string
     */
    private function responseText($object, $content, $flag = 0) {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    /**
     * 微信审核方法
     * @return boolean
     */
    private function checkSignature() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = Config::get('xpz.wx_check_signature_token');
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取用户详细信息
     * @param $openid
     * @param $refer_id
     */
    private function createuserinfo($openid)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->getToken() . "&openid=" . $openid;
        $user = $this->request_get($url);
        Tool::mylog(Config::get('xpz.my_log_show'), "获取用户信息接口返回：", $url."<=》".$user,'wx_get_user');
        $user = json_decode($user, true);
        $users = array(
            'openid' => $openid,
            'nickname' => $user['nickname'],
            'avatar' => $user['headimgurl'],
            'email' => 'default@default.com',
            'sex' => $user['sex'],
            'unionid' => isset($user['unionid'])?$user['unionid']:"",
            'status' => 1,
            'reg_time' => $user['subscribe_time'],//关注公众号的时间
        );
        $user_str = date('Y-m-d H:i:s') . "\t";
        foreach ($users as $key => $value) {
            $user_str .= $key . '=' . $value . "\t";
        }
        $user_str .= "\n";
        Tool::mylog(Config::get('xpz.my_log_show'), "获取用户信息：", $user_str,'wx_user');
        return $users;
    }
    /**
     * @param $appid
     * @param $appsecret
     *
     * @return mixed
     * 获取token
     */
    private function getToken() {
        $wxtoken = new Wxtoken($this->appId, $this->appSecret);
        $token = $wxtoken->accessToken();
//        echo $token;
        return $token;
    }
    
    /**
     * 发送post请求
     *
     * @param string $url
     * @param string $param
     *
     * @return bool|mixed
     */
    private function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }

    /**
     * 发送get请求
     *
     * @param string $url
     *
     * @return bool|mixed
     */
    private function request_get($url = '') {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    private function http_post_data($url, $data_string) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        if (curl_errno($ch)) {
            $this->ErrorLogger('curl falied. Error Info: ' . curl_error($ch));
        }
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    /**
     * 通知工作人员审核用户请求通知
     * @param type $adminId
     */
    private function auditUserApply($adminId,$name){
        $touser = "o1WT56rjIh35F0eC1wpxgvo1DE5c";
        Tool::auditUserApplyNotice($touser, $name, $adminId);
    }
    //返回随机不重复字符串
    private function short_md5() {
        $str = Random::uuid();
        return substr(md5($str), 8, 16);
    }

    /**
     * 获取js部署代码
     * @param $openId
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getJsCode($openId){
        $contentStr = "获取js部署代码失败！";
        $userInfo = model("User")->where(['openid'=>$openId])->find();
        if(empty($userInfo['id'])){//请先关注公众号完成会员注册
            $contentStr = "请先关注公众号完成会员注册！";
        } else if(empty($userInfo['company_id'])) {//
            $contentStr = getRegCompanyA($openId,$userInfo['id']);
        } else {
            $chatstyleInfo = getChatStyleInfo($userInfo['company_id']);
            $token = Tool::en_token($userInfo['id'],$userInfo['company_id']);

            //获取分享口令
            $companyInfo = model("Company")->where(['id'=>$userInfo['company_id']])->find();
            $shareArr['douyin'] = $companyInfo['douyin'];
            $shareArr['kuaishou'] = $companyInfo['kuaishou'];
            $shareArr['taobao'] = $companyInfo['taobao'];
            $shareArr['tianmao'] = $companyInfo['tianmao'];
            $shareArr['albb'] = $companyInfo['albb'];

            $jsUrl = Tool::createJsCode($userInfo['company_id'], $token, $chatstyleInfo,$shareArr);
            $jsHtml = "<script src='".$jsUrl."'></script>";
            $contentStr = "<textarea>".$jsHtml."</textarea>";
        }
        return $contentStr;
    }

    private function getHelpContent(){
        $string = "1 帮助\r\n2 完善公司信息\r\n3 获取客服代码\r\n友情提示：输入数字获取相应功能";
        return $string;
    }

}
